package com.java.basis.thread.cas;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author wangning
 * @create 2022-01-29 10:53
 * CAS锁
 *
 */
@Slf4j(topic = "c.LockCas")
public class LockCas {
	private AtomicInteger state = new AtomicInteger(0);

	//0-没加锁，1-加锁
	//加锁
	public void lock() {
		while (true) {
			if (state.compareAndSet(0, 1)) {
				break;
			}
		}
	}

	//解锁
	public void unlock() {
		log.debug("unlock...");
		state.set(0);
	}

	public static void main(String[] args) {
		LockCas lock = new LockCas();
		new Thread(() -> {
			log.debug("begin...");
			lock.lock();
			try {
				log.debug("lock...");
				Thread.sleep(1000);

			} catch (InterruptedException e) {
				e.printStackTrace();
			} finally {
				lock.unlock();
			}
		}, "t1").start();

		new Thread(() -> {
			log.debug("begin...");
			lock.lock();
			try {
				log.debug("lock...");
			} finally {
				lock.unlock();
			}
		}, "t2").start();
	}
}
